package com.ilancuo.template.singleton;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 既能够保证延迟加载,又能保证原子性及实例的唯一性
 *
 * Created by ilancuo on 2018/9/4.
 */
public class AtomicSingleton {
    private static AtomicReference<AtomicSingleton> INSTANCE = new AtomicReference<>();

    private AtomicSingleton() {

    }

    public static AtomicSingleton getInstance() {
        AtomicSingleton current = INSTANCE.get();
        for (; ; ) {
            if (current != null)
                return current;
            current = new AtomicSingleton();
            if (INSTANCE.compareAndSet(null, current)) {
                return current;
            }
        }
    }
}
